# -*- coding: utf-8 -*-
import logging
import os
from datetime import datetime
from logging.handlers import RotatingFileHandler


def setup_logger(query):
    """
    设置日志记录器
    """
    os.makedirs("logs", exist_ok=True)
    log_file_name = f"logs/{query.replace('=', '_').replace('\'', '').replace('\"', '')}_{datetime.now().strftime('%Y%m%d')}.log"

    logger = logging.getLogger(query)
    logger.setLevel(logging.INFO)

    # 设置文件处理程序，最大文件大小为10MB，保留3个备份文件
    file_handler = RotatingFileHandler(
        log_file_name,
        maxBytes=10 * 1024 * 1024,  # 10 MB
        backupCount=3
    )

    formatter = logging.Formatter(
        '%(asctime)s - %(levelname)s - [Thread:%(threadName)s] - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    file_handler.setFormatter(formatter)

    logger.addHandler(file_handler)

    return logger
